<template>
  <div class="wrap">
    <div v-loading="loading" class="b-cont b-cont-ers">
      <sections
        v-for="(mainItem, mainIndex) in list"
        :key="mainIndex"
        :title="mainItem.name"
        class="b-cells"
        content-height="auto"
      >
        <el-form
          :model="editForm"
          :rules="editRules"
          :ref="`editForm${mainIndex}`"
          class="el-form--flex"
          label-position="left"
          label-width="130px"
        >
          <el-form-item
            v-for="(item, index) in mainItem.list"
            :key="index"
            :prop="item.fieldName"
            :class="{ 'is-block': isBlockShowField(item) }"
          >
            <span slot="label">
              {{ item.name }}
            </span>
            <template v-if="item.isEdit">
              <el-input
                v-if="
                  item.formType === 'text' ||
                  item.formType == 'number' ||
                  item.formType == 'floatnumber' ||
                  item.formType == 'mobile' ||
                  item.formType == 'email' ||
                  item.formType == 'textarea' ||
                  item.formType == 'number_input'
                "
                v-model="editForm[item.fieldName]"
              />
              <!-- <wk-payment-select
                v-else-if="item.fieldName == 'returnType'"
                :formType="item.formType"
                v-model="editForm[item.fieldName]"
                :value="editForm[item.fieldName]"
                :editVal="item.value"
                @stage="arrayPayValueChange($event, item, index)"
              /> -->
              <!-- 开户行所在地 -->
              <v-distpicker
                v-else-if="item.fieldName == 'mapBankcardaddr'"
                :province="editForm[item.fieldName].province"
                :city="editForm[item.fieldName].city"
                :area="editForm[item.fieldName].area"
                @province="selectProvince($event, item, index)"
                @city="selectCity($event, item, index)"
                @area="selectArea($event, item, index)"
              />
              <el-select
                v-else-if="
                  item.formType === 'select' ||
                  item.formType === 'business_status'
                "
                v-model="editForm[item.fieldName]"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(item, index) in getFieldOption(item)"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
              <el-select
                v-else-if="item.formType === 'checkbox'"
                v-model="editForm[item.fieldName]"
                multiple
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(item, index) in getFieldOption(item)"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
              <el-date-picker
                v-else-if="item.formType === 'date'"
                v-model="editForm[item.fieldName]"
                type="date"
                clearable
                style="width: 100%"
                value-format="yyyy-MM-dd"
              />
              <el-date-picker
                v-else-if="item.formType === 'datetime'"
                v-model="editForm[item.fieldName]"
                clearable
                style="width: 100%"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
              <user-Select
                v-model="editForm[item.fieldName]"
                v-else-if="['single_user', 'user'].includes(item.formType)"
                :restrictData="item.restrictData"
                style="width: 100%"
              >
              </user-Select>
              <!-- 多级下拉 -->
              <level-select
                v-else-if="item.formType == 'leve_linkage'"
                :value="editOptions[item.fieldName].levelData"
                :editVal="editForm[item.fieldName]"
                @stage="stageChange($event, item.fieldName)"
              >
              </level-select>

              <xh-structure-cell
                v-else-if="item.formType === 'structure'"
                :value="editForm[item.fieldName]"
                :radio="false"
                @value-change="arrayValueChange($event, item)"
              />

              <wkstage-select
                v-else-if="
                  ['major_select', 'industry_select'].includes(item.formType)
                "
                :formType="item.formType"
                :editVal="item.value"
                @stage="arrayValueChange($event, item, index)"
              />
              <wk-school-select
                v-else-if="item.formType == 'school_select'"
                :editVal="item.value"
                @school="arrayValueChange($event, item, index)"
              />
              <crm-relative-cell
                v-else-if="
                  item.formType === 'contacts' ||
                  item.formType === 'customer' ||
                  item.formType === 'contract' ||
                  item.formType === 'business'
                "
                :relative-type="item.formType"
                :value="editForm[item.fieldName]"
                @value-change="arrayValueChange($event, item)"
              />
              <xh-files
                v-else-if="item.formType === 'file'"
                :value="editForm[item.fieldName]"
                @value-change="arrayValueChange($event, item)"
              />
              <xh-prouct-cate
                v-else-if="item.formType === 'category'"
                :value="editForm[item.fieldName]"
                @value-change="arrayValueChange($event, item)"
              />
            </template>
            <template v-else>
              <flexbox v-if="item.formType === 'file'" style="min-height: 40px">
                <file-list-view :list="item.value || []" />
                <template v-if="item.fieldName !== 'fliedIjczva'">
                  <i
                    v-if="getEditAuth(item)"
                    class="wk wk-edit form-item__edit 55"
                    @click="editClick(item)"
                  />
                </template>
              </flexbox>
              <div
                v-else-if="item.formType === 'map_address'"
                :gutter="0"
                wrap="wrap"
              >
                <div :span="0.5" class="b-cell" @click="checkMapView(item)">
                  <flexbox class="b-cell-b">
                    <div class="b-cell-name">定位</div>
                    <div
                      class="b-cell-value"
                      style="color: #3e84e9; cursor: pointer"
                    >
                      {{ item.value.location }}
                    </div>
                  </flexbox>
                </div>
                <div :span="0.5" class="b-cell">
                  <flexbox class="b-cell-b">
                    <div class="b-cell-name">区域</div>
                    <div class="b-cell-value">{{ item.value.address }}</div>
                  </flexbox>
                </div>
                <div :span="0.5" class="b-cell">
                  <flexbox class="b-cell-b">
                    <div class="b-cell-name">详细地址</div>
                    <div class="b-cell-value">
                      {{ item.value.detailAddress }}
                    </div>
                  </flexbox>
                </div>
              </div>
              <!-- 合同相关产品 -->
              <div v-else-if="item.typeField == '合同相关产品'">
                <el-table
                  :data="proList"
                  :height="tableHeight"
                  :cell-class-name="cellClassName"
                  stripe
                  style="width: 100%; border: 1px solid #e6e6e6"
                  @row-click="handleRowClick"
                >
                  <el-table-column
                    v-for="(item, index) in fieldList"
                    :key="index"
                    :prop="item.prop"
                    :label="item.label"
                    :formatter="fieldFormatter"
                    show-overflow-tooltip
                    width="150"
                  />
                </el-table>
              </div>
              <div v-else-if="item.formType == 'receivablesList'">
                <el-table
                  :data="item.value"
                  :cell-class-name="cellClassName"
                  stripe
                  style="width: 100%; border: 1px solid #e6e6e6"
                >
                  <el-table-column prop="number" label="回款编号" width="180">
                  </el-table-column>
                  <el-table-column prop="money" label="回款金额" width="180">
                  </el-table-column>
                  <el-table-column prop="returnTime" label="回款时间">
                  </el-table-column>
                </el-table>
              </div>
              <div
                v-else
                :class="{ 'can-check': isModule(item) }"
                class="form-item__value"
              >
                <span
                  v-if="
                    getCommonShowValue(item) === '' ||
                    getCommonShowValue(item) === null
                  "
                >
                  --
                </span>
                <span @click="showDviewClick(item)" v-else>
                  {{ getCommonShowValue(item) }}</span
                >
                <template
                  v-if="
                    item.fieldName !== 'fliedGdcrxx' &&
                    item.fieldName !== 'num' &&
                    item.fieldName !== 'number'
                  "
                >
                  <i
                    v-if="getEditAuth(item)"
                    class="wk wk-edit form-item__edit"
                    @click.stop="editClick(item)"
                /></template>
              </div>
            </template>
          </el-form-item>
        </el-form>
      </sections>
      <slot />
      <map-view
        v-if="showMapView"
        :title="mapViewInfo.title"
        :lat="mapViewInfo.lat"
        :lng="mapViewInfo.lng"
        @hidden="showMapView = false"
      />
      <c-r-m-full-screen-detail
        :visible.sync="showFullDetail"
        :id="fullDetailId"
        :crm-type="fullDetailType"
      />
    </div>
    <div class="b-cont__handle" :class="showSaveButton ? 'b-cont__show' : ''">
      <el-button @click.native="editCancel">取消</el-button>
      <el-button v-debounce="editConfirm" type="primary">保存</el-button>
    </div>
  </div>
</template>

<script>
import { crmContractProductAPI } from "@/api/crm/contract";
import {
  filedGetInformationAPI,
  filedUpdateTableFieldAPI,
  filedValidatesAPI,
} from "@/api/crm/common";

import {
  XhUserCell,
  XhStructureCell,
  XhFiles,
  CrmRelativeCell,
  XhProuctCate,
  XhBusinessStatus,
  XhReceivablesPlan,
} from "@/components/CreateCom";
import WkstageSelect from "@/components/NewCom/WkstageSelect";
import WkSchoolSelect from "@/components/NewCom/WkSchoolSelect";
import crmTypeModel from "@/views/crm/model/crmTypeModel";
import Sections from "../components/Sections";
import MapView from "@/components/MapView"; // 地图详情
import FileListView from "@/components/FileListView";
import CheckStatusMixin from "@/mixins/CheckStatusMixin";
import { separator } from "@/filters/vueNumeralFilter/filters";
import UserSelect from "@/views/admin/components/UserSelect"; // 人员单选
import {
  regexIsCRMNumber,
  regexIsNumber,
  regexIsCRMMoneyNumber,
  regexIsCRMMobile,
  regexIsCRMEmail,
  objDeepCopy,
} from "@/utils";
import { isArray, isObject, isEmpty } from "@/utils/types";
import { mapGetters } from "vuex";
import { getWkDateTime } from "@/utils";
import WkPaymentSelect from "@/components/NewCom/WkPaymentSelect";
import LevelSelect from "@/components/NewCom/LevelSelect";
import VDistpicker from "@/components/VDistpicker";
export default {
  // 学员管理 的 基本信息
  name: "CRMEditBaseInfo",
  components: {
    Sections,
    MapView,
    FileListView,
    XhUserCell,
    XhStructureCell,
    XhFiles,
    CrmRelativeCell,
    XhProuctCate,
    XhBusinessStatus,
    XhReceivablesPlan,
    WkstageSelect,
    WkSchoolSelect,
    CRMFullScreenDetail: () => import("@/components/CRMFullScreenDetail"),
    WkPaymentSelect,
    UserSelect,
    LevelSelect,
    VDistpicker,
  },
  filters: {},
  mixins: [CheckStatusMixin],
  props: {
    // 模块ID
    id: [String, Number],
    poolId: [String, Number],
    isSeas: {
      type: Boolean,
      default: false,
    },
    detail: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // 没有值就是全部类型 有值就是当个类型
    crmType: {
      type: String,
      default: "",
    },
    // 固定字段的数据
    filedList: Array,
  },
  data() {
    return {
      loading: false,
      list: [],
      // 控制展示地图详情
      showMapView: false,
      // 地图详情信息
      mapViewInfo: {},
      showFullDetail: false,
      fullDetailId: "",
      fullDetailType: "",
      // 编辑
      showSaveButton: false,
      editRules: {},
      editForm: {},
      editOptions: {},
      editFieldData: [],
      fieldList: [],
      proList: [],
      tableHeight: "300px",
      contractIdForReceivables: 0,
    };
  },
  inject: ["rootTabs"],
  computed: {
    ...mapGetters(["crm"]),
  },
  watch: {
    id(val) {
      if (!this.filedList) {
        this.refreshData(true);
      }
    },

    filedList() {
      this.list = this.filedList;
    },

    "rootTabs.currentName"(val) {
      if (val === "CRMEditBaseInfo") {
        this.refreshData(false);
      }
    },
  },
  created() {
    this.$bus.on("crm-detail-update", (data) => {
      this.getBaseInfo(false);
      if (!this.isSeas) {
        this.refreshData(true);
      }
    });
    this.getFieldList();
  },
  beforeDestroy() {
    this.$bus.off("crm-detail-update");
  },
  mounted() {
    if (this.filedList) {
      this.list = this.filedList;
    } else {
      this.refreshData(true);
    }
  },
  methods: {
    /**
     * 选择省市区
     */
    selectProvince(data, item, index) {
      this.editForm[item.fieldName] = this.adrHandle(
        0,
        this.editForm[item.fieldName],
        data.value
      );
    },
    selectCity(data, item, index) {
      this.editForm[item.fieldName] = this.adrHandle(
        1,
        this.editForm[item.fieldName],
        data.value
      );
    },
    selectArea(data, item, index) {
      this.editForm[item.fieldName] = this.adrHandle(
        2,
        this.editForm[item.fieldName],
        data.value
      );
    },
    adrHandle(index, _arr, val) {
      let arr;
      if (Object.prototype.toString.call(_arr) === "[object Object]") {
        arr = _arr;
        if (index === 0) arr.province = val;
        else if (index === 1) arr.city = val;
        if (index === 2) arr.area = val;
      } else {
        arr = _arr.split(",");
        if (arr.length > index) {
          arr[index] = val;
        } else {
          arr.push(val);
        }
        arr = arr.join(",");
      }

      return arr;
    },
    /**
     * 刷新页面数据
     */
    refreshData(loading = false) {
      this.getBaseInfo(loading);
    },
    showDviewClick(item) {
      const crm = this.$store.getters.crm;
      if (item.fieldName == "customerId") {
        this.fullDetailId = this.detail.customerId;
        this.fullDetailType = "customer";
        this.showFullDetail = true;
      } else if (item.fieldName == "contractId") {
        this.fullDetailId = this.detail.contractId;
        this.fullDetailType = "contract";
        this.showFullDetail = true;
      }
    },
    /**
     * 获取基础信息
     */
    getBaseInfo(loading) {
      this.loading = !!loading;
      const _this = this;
      const params = {
        types:
          this.crmType == "vipStudents" ? "vip" : crmTypeModel[this.crmType],
        id: this.id,
      };
      // 如果有公海id 需上传确定展示字段
      if (this.poolId) {
        params.poolId = this.poolId;
      }
      filedGetInformationAPI(params)
        .then((res) => {
          this.getEditFieldData(res);
          const baseList = [];
          const systemList = [];
          const arr1 = [];
          const contact = [];
          const arr2 = [];
          const productList = [];
          var isQueryProduct = false;
          res.data.forEach((item) => {
            // 回款还款区分
            if (this.detail.defaultGenerate) {
              if (item.fieldName == "money") return;
            } else {
              if (item.fieldName == "dueMoney") return;
            }
            // end
            if (item.formType === "floatnumber") {
              item.value = separator(item.value);
            } else if (item.formType === "date") {
              item.value = getWkDateTime(item.value);
            }
            if (_this.crmType == "contacts") {
              if (item.typeField == "基本信息") {
                baseList.push(item);
              } else if (item.typeField == "联系信息") {
                contact.push(item);
              } else if (item.typeField == "学员状态") {
                arr1.push(item);
              } else if (item.typeField == "设计类") {
                arr2.push(item);
              } else {
                systemList.push(item);
              }
              this.list = [
                {
                  name: "基本信息",
                  list: baseList,
                },
                {
                  name: "联系信息",
                  list: contact,
                },
                {
                  name: "学员状态",
                  list: arr1,
                },
                {
                  name: "设计类",
                  list: arr2,
                },
                {
                  name: "系统信息",
                  list: systemList,
                },
              ];
            } else if (_this.crmType == "receivables") {
              if (item.fieldName == "contractId") {
                this.contractIdForReceivables = item.value["contractId"];
              }
              if (item.typeField == "合同相关产品") {
                isQueryProduct = true;
                productList.push(item);
              } else if (item.sysInformation == 0) {
                baseList.push(item);
              } else {
                systemList.push(item);
              }
              if (productList.length > 0) {
                this.list = [
                  {
                    name: "基本信息",
                    list: baseList,
                  },
                  {
                    name: "产品信息",
                    list: productList,
                  },
                  {
                    name: "系统信息",
                    list: systemList,
                  },
                ];
              } else {
                this.list = [
                  {
                    name: "基本信息",
                    list: baseList,
                  },
                  {
                    name: "系统信息",
                    list: systemList,
                  },
                ];
              }
            } else {
              if (item.sysInformation == 0) {
                baseList.push(item);
              } else {
                systemList.push(item);
              }
              this.list = [
                {
                  name: "基本信息",
                  list: baseList,
                },
                {
                  name: "系统信息",
                  list: systemList,
                },
              ];
            }
          });
          if (isQueryProduct == true) {
            this.getProductList();
          }
          this.editCancel();
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //获取产品
    getProductList() {
      crmContractProductAPI({
        contractId: this.contractIdForReceivables,
        pageType: 0,
      })
        .then((res) => {
          this.proList = res.data.list;
        })
        .catch(() => {});
    },
    /**
     * 查看地图详情
     */
    checkMapView(item) {
      if (item.value && item.value !== "") {
        this.mapViewInfo = {
          title: item.value.location,
          lat: item.value.lat,
          lng: item.value.lng,
        };
        this.showMapView = true;
      }
    },

    getArrayKey(type) {
      if (type === "structure") {
        return "name";
      } else if (type === "user") {
        return "realname";
      }

      return "";
    },

    arrayValue(array, field) {
      if (
        !array ||
        Object.prototype.toString.call(array) !== "[object Array]"
      ) {
        return "";
      }

      return array
        .map((item) => {
          return field ? item[field] : item;
        })
        .join("，");
    },

    /**
     * 学员等模块类型
     */
    isModule(item) {
      return ["customer", "business", "contract", "contacts"].includes(
        item.formType
      );
    },

    /**
     * 特殊字段
     */
    isSpecialField(item) {
      return ["category", "statusName", "typeName"].includes(item.formType);
    },

    /**
     * 是整行展示字段
     */
    isBlockShowField(item) {
      return ["map_address", "file"].includes(item.formType);
    },

    getShowBlock(type) {
      return ["map_address", "file"].includes(type);
    },

    getModuleName(item) {
      const field = {
        customer: "customerName",
        business: "businessName",
        contract: "contractNum",
        contacts: "contactsName",
        category: "categoryName",
        statusName: "statusName",
        typeName: "typeName",
      }[item.formType];
      return item.value ? item.value[field] : "";
    },

    getFieldOption(item) {
      const editData = this.editOptions[item.fieldName];
      let setting = [];
      if (editData) {
        if (item.formType === "select" || item.formType === "checkbox") {
          if (
            editData.setting.length > 0 &&
            typeof editData.setting[0] == "string"
          ) {
            setting = editData.setting.map((element) => {
              return { name: element, value: element };
            });
          } else {
            setting = editData.setting;
          }
        } else if (item.formType === "business_status") {
          setting = editData.setting.map((element) => {
            element.value = element.statusId;
            return element;
          });
        }
      }

      return setting;
    },

    /**
     * 获取非附件类型的展示值
     */
    getCommonShowValue(item) {
      if (item.fieldName == "studentId") {
        return item.value.studentName || "";
      }
      if (item.fieldName == "mapBankcardaddr") {
        if (item.value && item.value.province) {
          return (
            item.value.province + "-" + item.value.city + "-" + item.value.area
          );
        } else {
          return "";
        }
      }
      if (item.fieldName == "isTransform") {
        return ["否", "是"][item.value] || "";
      } else if (this.isModule(item) || this.isSpecialField(item)) {
        return this.getModuleName(item);
      } else if (item.formType === "single_user") {
        return item.value ? item.value.realname : "";
      } else if (
        item.formType === "checkbox" ||
        item.formType === "structure" ||
        item.formType === "user"
      ) {
        return this.arrayValue(item.value, this.getArrayKey(item.formType));
      } else if (item.formType === "check_status") {
        return this.getStatusName(item.value);
      } else if (item.fieldName === "createDeptId") {
        //创建人所在部门
        return item.value ? item.value.createDeptName : "";
      } else if (item.fieldName === "ownerDeptId") {
        //负责人所在部门
        return item.value ? item.value.ownerDeptName : "";
      } else if (item.fieldName === "studentStatus") {
        //学员状态
        return item.value === 0 ? "已退学" : item.value == 1 ? "已入学" : "--";
      }
      return item.value;
    },

    /**
     * 查看详情
     */
    checkModuleDetail(data) {
      if (this.isModule(data) && isObject(data.value)) {
        this.fullDetailType = data.formType;
        this.fullDetailId = data.value[`${data.formType}Id`];
        this.showFullDetail = true;
      }
    },

    /**
     * 编辑逻辑
     */
    getEditAuth(item) {
      if (
        this.isSeas ||
        (this.detail.isTransform == 1 &&
          !this.$store.state.user.userInfo.isAdmin)
      ) {
        return false;
      }
      if (
        this.crmType == "business" &&
        ["statusName", "typeName"].includes(item.formType)
      ) {
        return false;
      } else if (
        this.crmType == "contract" &&
        ["business", "contacts", "customer"].includes(item.formType)
      ) {
        return false;
      } else if (
        this.crmType == "receivables" &&
        ["contract", "customer"].includes(item.formType)
      ) {
        return false;
      } else if (
        this.crmType == "visit" &&
        ["business", "contacts", "customer"].includes(item.formType)
      ) {
        return false;
      } else if (this.crmType == "overdue") {
        return false;
      }
      // authLevel 1 不能查看不能编辑 2可查看  3 可编辑可查看
      return (
        item.authLevel === 3 &&
        this.crm &&
        this.crm[this.crmType] &&
        this.crm[this.crmType].update
      ); // 不能编辑 disabled true
    },

    /**
     * 点击编辑按钮
     */
    editClick(item) {
      const editData = item;
      if (editData) {
        let value =
          isArray(editData.value) || isObject(editData.value)
            ? objDeepCopy(editData.value)
            : editData.value;
        if (
          item.formType === "contacts" ||
          item.formType === "customer" ||
          item.formType === "contract" ||
          item.formType === "business"
        ) {
          value = value && value[`${item.formType}Id`] ? [value] : [];
        } else if (item.formType === "category") {
          value = value && value.categoryId ? value.categoryId : [];
        } else if (item.formType === "single_user") {
          value = value && value.userId ? value.userId : "";
        } else if (
          item.formType === "structure" ||
          item.formType === "file" ||
          item.formType === "user"
        ) {
          value = value || [];
        }
        this.$set(this.editForm, item.fieldName, value);
        this.$set(editData, "isEdit", true);
        this.$set(this.editOptions, item.fieldName, editData);
      }
      console.log("测试打印表单---------this.editForm-------");
      console.log(this.editForm);
      console.log("测试打印表单---------this.editOptions-------");
      console.log(this.editOptions);
      this.showSaveButton = true;
      this.$set(item, "isEdit", true);
    },

    editCancel() {
      if (this.$refs.editForm0[0].clearValidate) {
        this.$refs.editForm0[0].clearValidate();
      }

      this.$nextTick(() => {
        this.list.forEach((bItem) => {
          bItem.list.forEach((item) => {
            item.isEdit = false;
          });
        });
        this.editFieldData.forEach((item) => {
          item.isEdit = false;
        });

        this.editForm = {};
        this.editOptions = {};
        this.showSaveButton = false;
      });
    },

    editConfirm() {
      // customerId    fieldId   fieldType  fieldName  formType  value
      // this.editCancel()
      this.$refs.editForm0[0].validate((valid) => {
        if (valid) {
          this.submiteInfo();
        }
      });
    },

    /**
     * 发请求提交数据
     */
    submiteInfo() {
      // 仅第一块可编辑 ，直接取第一块的数据
      this.loading = true;
      let fields = [];
      let len = this.list.length;
      if (this.list.length == 2) {
        fields = this.list[0].list.concat(this.list[1].list) || [];
      } else {
        this.list.forEach((item, index) => {
          fields = fields.concat(item.list) || [];
          // console.log(fields)
        });
        // fields =
        //   this.list[0].list
        //     .concat(this.list[1].list)
        //     .concat(this.list[2].list)
        //     .concat(this.list[3].list)
        //     .concat(this.list[4].list) || [];
      }
      // const fields = this.list[0].list.concat(this.list[1].list).concat(this.list[2].list).concat(this.list[3].list).concat(this.list[4].list) || []
      const list = [];
      for (let index = 0; index < fields.length; index++) {
        const field = fields[index];
        if (field.isEdit) {
          const fieldData = this.editOptions[field.fieldName];
          if (fieldData) {
            fieldData.value = this.getRealValue(
              fieldData,
              this.editForm[field.fieldName]
            );
            list.push(fieldData);
          }
        }
      }

      filedUpdateTableFieldAPI({
        id: this.id,
        batchId: this.detail.batchId,
        label: crmTypeModel[this.crmType],
        list: list,
      })
        .then((res) => {
          this.loading = false;
          this.editCancel();
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: res.msg,
            });
            this.$emit("on-handle");
          }

          this.refreshData(true);
        })
        .catch(() => {
          this.loading = false;
        });
    },

    getRealValue(element, value) {
      if (
        element.formType == "customer" ||
        element.formType == "contacts" ||
        element.formType == "business" ||
        element.formType == "leads" ||
        element.formType == "contract"
      ) {
        if (value && value.length) {
          return value[0][`${element.formType}Id`];
        } else {
          return "";
        }
      } else if (element.formType == "single_user") {
        return value;
      } else if (
        element.formType == "user" ||
        element.formType == "structure"
      ) {
        return value
          .map((item) => {
            return element.formType == "user" ||
              element.formType == "single_user"
              ? item.userId
              : item.id;
          })
          .join(",");
      } else if (element.formType == "file") {
        if (value && value.length > 0) {
          return value[0].batchId;
        }
        return "";
      } else if (element.formType == "category") {
        if (value && value.length > 0) {
          return value[value.length - 1];
        }
        return "";
      } else if (element.formType == "checkbox") {
        if (value && value.length > 0) {
          return value.join(",");
        }
        return "";
      }

      return value;
    },
    /**
     * 多级下拉编辑
     */
    stageChange(e, name) {
      this.editForm[name] = e;
    },
    /**
     * 员工编辑
     * 关联模块编辑
     * 附件选择
     * 产品类别
     */
    arrayValueChange(data, item) {
      this.editForm[item.fieldName] = data.value || [];
    },
    arrayPayValueChange(data, item) {
      this.editForm[item.fieldName] = data || [];
    },
    // 获取自定义字段
    getEditFieldData(res) {
      const editRules = {};
      let editFieldData = res.data;
      editFieldData.forEach((item) => {
        item.isEdit = false;
        const authList = this.getItemRulesArrayFromItem(item);
        if (authList && authList.length) {
          editRules[item.fieldName] = authList;
        }
      });

      this.editFieldData = editFieldData;
      this.editRules = editRules;
    },
    /**
     * 不验证字段必填
     */
    ingnoreRequiredField(data) {
      if (this.crmType == "contract" && data.fieldName == "num") {
        return data.autoGeneNumber == 1;
      } else if (this.crmType == "receivables" && data.fieldName == "number") {
        return data.autoGeneNumber == 1;
      } else if (this.crmType == "visit" && data.fieldName == "visit_number") {
        return data.autoGeneNumber == 1;
      }

      return false;
    },

    /**
     * item 当行数据源
     */
    getItemRulesArrayFromItem(item) {
      var tempList = [];
      // 验证必填
      if (item.isNull == 1 && !this.ingnoreRequiredField(item)) {
        var validateIsNull = (rule, value, callback) => {
          if (!rule.item || !rule.item.isEdit) {
            return callback();
          }
          if (isEmpty(value)) {
            callback(new Error(item.name + "不能为空"));
          } else {
            callback();
          }
        };
        tempList.push({
          validator: validateIsNull,
          item: item,
          trigger: [],
        });
      }

      // 验证唯一
      if (item.isUnique == 1) {
        var validateUnique = (rule, value, callback) => {
          if ((isArray(value) && value.length == 0) || !value) {
            callback();
          } else {
            var validatesParams = {};
            validatesParams.fieldId = item.fieldId;
            if (isArray(value)) {
              let postValue = "";
              if (value.length > 0) {
                if (
                  rule.item.formType == "user" ||
                  rule.item.formType == "single_user" ||
                  rule.item.formType == "structure"
                ) {
                  postValue = value
                    .map((valueItem) => {
                      return rule.item.formType == "user" ||
                        rule.item.formType == "single_user"
                        ? valueItem.userId
                        : valueItem.id;
                    })
                    .join(",");
                } else if (rule.item.fieldName == "categoryId") {
                  if (value && value.length) {
                    postValue = value[value.length - 1];
                  } else {
                    postValue = "";
                  }
                } else if (rule.item.formType == "checkbox") {
                  postValue = value.join(",");
                }
              }
              validatesParams.value = postValue;
            } else {
              validatesParams.value = value;
            }
            validatesParams.batchId = this.detail.batchId;
            filedValidatesAPI(validatesParams)
              .then((res) => {
                // status 1 通过 0
                if (res.data.status === 1) {
                  callback();
                } else {
                  callback(new Error(item.name + "已存在"));
                }
              })
              .catch((error) => {
                callback(new Error(error.msg ? error.msg : "验证出错"));
              });
          }
        };
        tempList.push({
          validator: validateUnique,
          item: item,
          trigger:
            item.formType == "checkbox" || item.formType == "select" ? [] : [],
        });
      }

      // 特殊字符
      if (item.formType == "number_input") {
        //训练营期数
        let reg3 = new RegExp("^[0-9]*$");
        var validateCRMNumber1 = (rule, value, callback) => {
          if (!rule.item || !rule.item.isEdit) {
            return callback();
          }
          if (!value || value == "" || reg3.test(value)) {
            callback();
          } else {
            callback(new Error("必须为数字"));
          }
        };
        tempList.push({
          validator: validateCRMNumber1,
          item: item,
          trigger: [],
        });
      } else if (item.formType == "number") {
        var validateCRMNumber = (rule, value, callback) => {
          if (!rule.item || !rule.item.isEdit) {
            return callback();
          }
          if (!value || value == "" || regexIsCRMNumber(value)) {
            callback();
          } else {
            callback(new Error("数字的整数部分须少于15位，小数部分须少于4位"));
          }
        };
        tempList.push({
          validator: validateCRMNumber,
          item: item,
          trigger: [],
        });
      } else if (item.formType == "floatnumber") {
        var validateCRMMoneyNumber = (rule, value, callback) => {
          if (!rule.item || !rule.item.isEdit) {
            return callback();
          }
          if (!value || value == "" || regexIsCRMMoneyNumber(value)) {
            callback();
          } else {
            callback(new Error("货币的整数部分须少于15位，小数部分须少于2位"));
          }
        };
        tempList.push({
          validator: validateCRMMoneyNumber,
          item: item,
          trigger: [],
        });
      } else if (item.formType == "mobile") {
        var validateCRMMobile = (rule, value, callback) => {
          if (!rule.item || !rule.item.isEdit) {
            return callback();
          }
          if (!value || value == "" || regexIsCRMMobile(value)) {
            callback();
          } else {
            callback(new Error("手机格式有误"));
          }
        };
        tempList.push({
          validator: validateCRMMobile,
          item: item,
          trigger: [],
        });
      } else if (item.formType == "email") {
        var validateCRMEmail = (rule, value, callback) => {
          if (!rule.item || !rule.item.isEdit) {
            return callback();
          }
          if (!value || value == "" || regexIsCRMEmail(value)) {
            callback();
          } else {
            callback(new Error("邮箱格式有误"));
          }
        };
        tempList.push({
          validator: validateCRMEmail,
          item: item,
          trigger: [],
        });
      }
      return tempList;
    },
    getFieldList() {
      this.fieldList.push({
        prop: "productName",
        width: "200",
        label: "产品名称",
      });
      this.fieldList.push({
        prop: "categoryName",
        width: "200",
        label: "产品类别",
      });
      this.fieldList.push({ prop: "unit", width: "200", label: "单位" });
      this.fieldList.push({ prop: "price", width: "200", label: "标准价格" });
      this.fieldList.push({ prop: "salesPrice", width: "200", label: "售价" });
      this.fieldList.push({ prop: "num", width: "200", label: "数量" });
      this.fieldList.push({
        prop: "discount",
        width: "200",
        label: "折扣（%）",
      });
      this.fieldList.push({ prop: "subtotal", width: "200", label: "合计" });
    },

    fieldFormatter(row, column) {
      if (column.property == "price" || column.property == "salesPrice") {
        return separator(row[column.property] || 0);
      }
      if (column.property == "unit") {
        if (row.unit == null) {
          row.unit = "无";
        }
      }
      return row[column.property];
    },
    /**
     * 当某一行被点击时会触发该事件
     */
    handleRowClick(row, column, event) {
      if (column.property == "productName") {
        this.fullDetailId = row.productId;
        this.fullDetailType = "product";
        this.showFullDetail = true;
      }
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === "productName") {
        return "can-visit--underline";
      } else {
        return "";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.wrap {
  position: relative;
  padding: 15px 0;
  height: 100%;
  width: 100%;
}
.b-cont {
  position: relative;
  padding: 15px 0;
  height: calc(100% - 40px);
  width: 100%;
  overflow-y: auto;
  overflow-y: overlay;
}

.b-cont__handle {
  position: absolute;
  text-align: right;
  right: 20px;
  width: 100%;
  z-index: 3;
  height: 47px;
  line-height: 47px;
  background: #f7f8fa;
  visibility: hidden;
}
.b-cont__show {
  visibility: visible !important;
}

.section {
  margin-top: 0;
  /deep/ .content {
    overflow: hidden;
  }
}

.b-cells + .b-cells {
  margin-top: 15px;
}

.b-cell {
  padding: 0 10px;
}

.el-form--flex {
  margin: 15px 10px 0 0;
  /deep/ .el-form-item {
    padding: 0 40px 0 15px;
    // margin-bottom: 10px;
    max-width: 100%;
    .el-form-item__content {
      position: relative;
      min-height: 40px;
    }

    .el-form-item__label {
      color: #333;
      font-size: 13px;
      line-height: 40px;
    }

    &:hover {
      .form-item__edit {
        display: inline;
      }
    }
  }
}

.form-item__value {
  font-size: 13px;
  color: #666;
  line-height: 40px;
  // white-space: pre-wrap;
  word-wrap: break-word;
  word-break: break-all;
}

.form-item__edit {
  margin-left: 5px;
  font-size: 14px;
  color: #999;
  cursor: pointer;
  display: none;
  flex-shrink: 0;

  &:hover {
    color: $xr-color-primary;
  }
}

.can-check {
  color: $xr-color-primary !important;
  cursor: pointer;
}

.is-block {
  flex-basis: 100% !important;
}

.b-cell-b {
  width: auto;
  .b-cell-name {
    width: 100px;
    margin-right: 10px;
    font-size: 13px;
    flex-shrink: 0;
    color: #777;
  }
  .b-cell-value {
    font-size: 13px;
    color: #333;
    line-height: 30px;
    white-space: pre-wrap;
    word-wrap: break-word;
    word-break: break-all;
  }
}
</style>
